import axios from '../utils/request'

export function login (username,password){
    return axios.post('/api/v1/auth/login',{
        username,
        password,
    })
}


export function reg(user){
    return axios.post('/api/v1/auth/reg',user)
}


//加入购物车
//第一个参数是商品信息，第二个参数是商品数量
export function addToShopCart (product,quantity) {
    //先获取购物车
    let myCart = getShopCart();
    //查询条件
    const index = myCart.findIndex(cart => cart.product == product)
    if(index > -1) {
        //如果有数量加1
        myCart[index].quantity = myCart[index].quantity + quantity;
    }else{
        //如果没有添加进去，数量加+1
        myCart.push({
            product,
            quantity,
        })
    }
    localStorage.setItem('my-shopcart' , JSON.stringify(myCart))
}


export function delFromproducts (product){
    let myCart = getShopCart();
    const index = myCart.findIndex(cart => cart.product == product)
    if(index > -1){
        myCart.splice(index,1)
    }
    localStorage.setItem('my-shopcart' , JSON.stringify(myCart))
}



export function getShopCart(){
    if(localStorage.getItem('my-shopcart')){
        return JSON.parse(localStorage.getItem('my-shopcart'))
    }else{
        return []
    }
}


export function getShopCartCount (){
    const myCarts = getShopCart();
    let resulet = 0;
    myCarts.forEach(item => resulet+=item.quantity)
        return resulet
}
